package com.devin.controller;

import com.devin.pojo.Product;
import com.devin.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/getProducts")
    public ModelAndView getProducts(@RequestParam(value = "page",defaultValue = "1")Integer page
            ,@RequestParam(value = "size",defaultValue = "5")Integer size){
        List<Product> products = productService.getProducts(page, size);
        PageInfo<Product> productPageInfo = new PageInfo<>(products);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productPageInfo",productPageInfo);
        modelAndView.setViewName("pages/product-pages-list");
        return modelAndView;
    }
    @RequestMapping(value = "/toAddProduct",method = RequestMethod.GET)
    public String toAddProduct(){
        return "pages/product-add";
    }
    @RequestMapping("/addProduct")
    public String addProduct(Product product){
        productService.addProduct(product);
        return "redirect:/products/getProducts";
    }

    @RequestMapping("/toUpdateProduct")
    public ModelAndView toUpdateProduct(Integer productId){
        Product product =productService.toUpdateProduct(productId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("product",product);
        modelAndView.setViewName("pages/product-update");
        return modelAndView;
    }

    @RequestMapping("/updateProduct")
    public String updateProduct(Product product){
        productService.updateProduct(product);
        return "redirect:/products/getProducts";
    }
    @RequestMapping(value = "/delProduct",method = RequestMethod.GET)
    public String delProduct(Integer productId){
        productService.delProduct(productId);
        return  "redirect:/products/getProducts";
    }
    @RequestMapping("/delProductsChecked")
    public String delProductsChecked(Integer[] ids){
        productService.delProductsChecked(ids);
        return  "redirect:/products/getProducts";
    }
}
